Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Amazon Medium Problems
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Maximize Distance to Closest Person

Problem Statement

You are given a binary array seats representing the row of seats, where seats[i] = 0 represents that the ith seat is empty, and seats[i] = 1 represents a person sitting in the ith seat. It is given that seats array contains at least one 1 and 0.

You want to sit in any seat such that the distance between you and the closest person to you is maximized.

Return that maximum distance to the closest person.

Examples

  • Example 1:

    • Input: seats = [1,0,0,0,1,0,0]
    • Expected Output: 2
    • Justification: The best seat is either of the two at the index 2 or 6, as they are both 2 seats away from the nearest occupied seat.
  • Example 2:

    • Input: seats = [1,0,0,0,0,1]
    • Expected Output: 2
    • Justification: The middle seats (index 2 or 3) are equally optimal, being 2 seats away from any occupied seat.
  • Example 3:

    • Input: seats = [0,1,0,1,0,1,0,0,0,0]
    • Expected Output: 4
    • Justification: The best position is at the end (index 9), which is 4 seats away from the nearest person.

Solution

To solve this problem, our approach focuses on calculating the distance between occupied seats and identifying the maximum gap for a person to sit. Initially, we'll scan the array to find the distances between all pairs of occupied seats. Additionally, we'll pay special attention to the edges of the array, where the distance calculation slightly varies because one side is bound by the array's end rather than another occupied seat. This method ensures we consider the maximum available distance at both the beginning and the end of the row.

The rationale behind this approach is that the optimal seat, in terms of distance to the closest person, is either between two occupied seats, at the beginning, or at the end of the row. By comparing these distances, we can determine the best seat. This method is effective because it directly calculates the relevant distances without unnecessary comparisons or iterations, making it efficient for solving the problem.

Step-by-step Algorithm

  1. Initialize Variables:

    • maxDistance to keep track of the maximum distance to the closest person. Initially set to 0.
    • lastOccupied to track the index of the last occupied seat encountered while iterating through the array. Initially set to -1 as a marker that no occupied seat has been encountered yet.
    • n to store the length of the seats array.
  2. Iterate Through the Seats:

    • Loop through each seat in the array using an index variable i.
  3. Check if Seat is Occupied:

    • If the current seat (seats[i]) is occupied (== 1), proceed to calculate the distance to the nearest person.
    • If it's the first occupied seat encountered (lastOccupied == -1), the distance is i itself, because it's the distance from the start to the first occupied seat.
    • Otherwise, calculate the distance as (i - lastOccupied) / 2. This accounts for the distance between two occupied seats, effectively finding the midpoint which gives the maximum distance to the closest person.
  4. Update lastOccupied:

    • Set lastOccupied to the current index i to mark the latest occupied seat.
  5. Check Distance from Last Occupied Seat to End:

    • After the loop completes, check if the distance from the last occupied seat to the end of the array (n - 1 - lastOccupied) is greater than the current maxDistance.
  6. Return maxDistance:

    • Return the maxDistance found as the maximum distance to the closest person.

Algorithm Walkthrough

Let's consider the input [0,1,0,1,0,1,0,0,0,0].

  • Start:

    • maxDistance = 0, lastOccupied = -1, n = 10
  • Iteration 0 (i = 0):

    • Seat is not occupied. No updates.
  • Iteration 1 (i = 1):

    • Seat is occupied. lastOccupied = -1 initially, so lastOccupied is updated to 1. Update maxDistance to 1
  • Iteration 2 (i = 2):

    • Seat is not occupied. No updates.
  • Iteration 3 (i = 3):

    • Seat is occupied. Calculate distance: (3 - 1) / 2 = 1. maxDistance remains 1. Update lastOccupied to 3.
  • Iteration 4 (i = 4):

    • Seat is not occupied. No updates.
  • Iteration 5 (i = 5):

    • Seat is occupied. Calculate distance: (5 - 3) / 2 = 1. maxDistance remains 1. Update lastOccupied to 5.
  • Iterations 6 to 9:

    • Seats are not occupied until the end. No updates to maxDistance or lastOccupied during these iterations.
  • After Loop:

    • Check distance from last occupied to end: 9 - 5 = 4. Since 4 is greater than maxDistance, update maxDistance to 4.
  • End:

    • maxDistance = 4 is returned as the maximum distance to the closest person.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity:

The algorithm iterates through the array exactly once to calculate the maximum distance to the closest person. Hence, the time complexity is linear with respect to the number of seats, n.

Space Complexity:

The space complexity is constant because the solutions use a fixed amount of space regardless of the input size.

Maximize Distance to Closest Person (medium)
Split Linked List in Parts (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity:

Space Complexity: